//
//  UINavigationController+SLKit.m
//  SLKit
//
//  Created by S_LINE on 2020/6/21.
//  Copyright © 2020 S_LINE. All rights reserved.
//

#import "UINavigationController+SLKit.h"

@implementation UINavigationController (SLKit)

+ (UINavigationController *)currentNavigationController
{
    if (![[UIApplication sharedApplication].windows.lastObject isKindOfClass:[UIWindow class]]) {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self getCurrentNavigationControllerFromViewController:rootViewController];
}

//递归
+ (UINavigationController *)getCurrentNavigationControllerFromViewController:(UIViewController *)vc
{
    if ([vc isKindOfClass:[UITabBarController class]]) {
        UINavigationController *nc = ((UITabBarController *)vc).selectedViewController;
        return [self getCurrentNavigationControllerFromViewController:nc];
    }
    else if ([vc isKindOfClass:[UINavigationController class]]) {
        if (((UINavigationController *)vc).presentedViewController) {
            return [self getCurrentNavigationControllerFromViewController:((UINavigationController *)vc).presentedViewController];
        }
        return [self getCurrentNavigationControllerFromViewController:((UINavigationController *)vc).topViewController];
    }
    else if ([vc isKindOfClass:[UIViewController class]]) {
        if (vc.presentedViewController) {
            return [self getCurrentNavigationControllerFromViewController:vc.presentedViewController];
        }
        else {
            return vc.navigationController;
        }
    }
    else {
        NSAssert(0, @"未获取到导航控制器");
        return nil;
    }
}

@end
